import MySQLdb
import sys

from config import config
from rule import Rule

class DB( object ):

    def __init__(self):
        self.db_user = config['db_user']
        self.db_pass = config['db_pass']
        self.db_data = config['db_data']
        self.db_port = config['db_port']

    def __doConnection(self):
        try:
            self.link   = MySQLdb.connect(user=self.db_user, passwd=self.db_pass, 
                                     db=self.db_data, port=self.db_port)
            cursor = self.link.cursor()
        except MySQLdb.Error, e: 
            print "Error en base de datos -> %d :: %s" % (e.args[0], e.args[1])
            sys.exit(1)

        return cursor

    def __closeConnection(self):
        try:
            self.link.close()
            return True
        except MySQLdb.Error, e:
            print "Error al cerrar la conexion -> %d :: %s" % (e.args[0], e.args[1])
            return False

    def getRules(self):
        rules  = list()
        cursor = self.__doConnection()
        sql    = "SELECT * FROM rule"
        cursor.execute(sql)
        result = cursor.fetchall()
        
        for rule in result:
            rules.append( Rule(rule[0], rule[1], rule[2], rule[3], rule[4], rule[5],
                               rule[6], rule[7], rule[8], rule[9]) )

        self.__closeConnection()
        return rules

    def ruleExist(self, cmprule):
        #import pdb;pdb.set_trace()
        rules   = self.getRules()
        iguales = 0

        for rule in rules:
            if rule == cmprule:
                iguales = iguales + 1

        if iguales > 0:
            return True
        else:
            return False

    def addRule(self, rule):
        if self.ruleExist(rule) is False:
            cursor        = self.__doConnection() 
            table         = (rule.getTable(),None)         [rule.getTable()       == None]
            source        = (rule.getSource(),None)        [rule.getSource()      == None]
            i_source      = (rule.getISource(), None)      [rule.getISource()     == None]
            destination   = (rule.getDestination(), None)  [rule.getDestination() == None]
            i_destination = (rule.getIDestination(), None) [rule.getIDestination()== None]
            protocol      = (rule.getProtocol(), None)     [rule.getProtocol()    == None]
            d_port        = (rule.getDPort(), None)        [rule.getDPort()       == None]
            target        = (rule.getTarget(), None)       [rule.getTarget()      == None]

            try:
                sql = """INSERT INTO rule (id,table_name,source,i_source,destination,i_destination,protocol,dport,target) VALUES (NULL,'%s','%s','%s','%s','%s','%s','%s','%s')""" % (table,
                      source,i_source,destination,i_destination,protocol,d_port,target)
                cursor.execute(sql)
                self.link.commit()
                self.__closeConnection()
                return True
            except MySQLdb.Error, e:
                print "Error al agregar la nueva regla -> %d :: %s" % (e.args[0], e.args[1])
                self.__closeConnection()
                return False
        else:
            return False


a = DB()
